from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializer import *
from user.serializer import OrderGoodsSer
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
import os
from rest_framework import viewsets
from rest_framework.generics import ListAPIView,RetrieveUpdateDestroyAPIView,CreateAPIView
import datetime
# 导入封装redis
from utils.redsi_con import redis_conn
# 加密，检查密码
from django.contrib.auth.hashers import make_password,check_password
# 导入生成token
from utils.token_utils import login_token
from django.db.models import Q
# Create your views here.
import json
from user.models import OrderModel
from user.serializer import OrderSer
# 商家视图
class ShopsView(viewsets.ViewSet):
    # 申请
    def shops_register(self,request):
        try:
            name = request.data.get("name")
            password = request.data.get("password")
            mobile = request.data.get("mobile")
            sms_code = request.data.get("sms_code")
            address = request.data.get("address")

            print("数据",name,password,mobile,sms_code,address)

            if not all([name,password,mobile,sms_code,address]):
                return Response({"code": 400, "message": "提交信息不完整！"})

            user = ShopsModel.objects.filter(name=name,is_delete=False).first()
            if user:
                return Response({"code": 204, "message": "名称已存在！"})

            user = ShopsModel.objects.filter(mobile=mobile,is_delete=False).first()
            if user:
                return Response({"code": 204, "message": "手机号已注册！"})

            hash_pwd = make_password(password)
            ShopsModel.objects.create(name=name, password=hash_pwd, mobile=mobile, address=address)
            return Response({"code":200,"message":"已提交申请！"})
        except Exception as e:
            print("错误",e)
            return Response({"code": 500, "message": "服务器错误！"})

    # 获取商家信息
    def shops_dict(self, request):
        try:
            user_id = request.session.get("shops_id")
            print(user_id)
            user = ShopsModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": 204, "message": "用户不存在！"})
            ser = ShopsSer(user)
            return Response({"code": 200, "message": "ok！","shops_dict":ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})

    #商家登录
    def logins(self,request):
        try:
            name = request.data.get("name")
            password = request.data.get("password")
            print("???看获取到没有>>>",name,password)
            try:
                shop = ShopsModel.objects.get(Q(name=name) & Q(password=password))
                print("??>>>>看看",shop,shop.password)
            except Exception as e:
                return Response({"code": 204, "message": "用户不存在"})
            if password==password:
                # 有权限登录站点
                payloads = {
                    "shop_id": shop.id,
                    "name": shop.name,
                }
                token, refresh_token = login_token(payloads)
                print("看看token生成了吗>>>", token)
                ser = ShopsSer(shop)
                return Response({
                    "code": 200,
                    "msg": "登录成功！",
                    "token": token,
                    "refresh_token": refresh_token,
                    "shop": ser.data,
                })

            return Response({"code": 204, "message": "用户名或密码错误！"})
        except Exception as e:
            print("错误",e)
            return Response({"code": 500, "message": "服务器错误！"})

#加载菜品类别
class ListCateAPIView(ModelViewSet):
    queryset = GoodTypeModel.objects.all()
    serializer_class = CateSer
    # # 重写list
    # def list(self,request,*args, **kwargs):
    #     try:
    #         data = GoodTypeModel.objects.filter(shops_id=id)
    #         ser = CateSer(data, many=True)
    #         return Response({"code": 200, "msg": "获取成功！", "data": ser.data})
    #     except Exception as e:
    #         print(e)
    #         return Response({"code": 500, "msg": "服务器错误！"})


# 加载菜品
class DishesClassifyViewSet(ModelViewSet):
    queryset = GoodModel.objects.all()
    serializer_class = DishesClassifySer
    lookup_url_kwarg = "pk"
    lookup_field = "pk"

# 展示所有商家
class Shops(ModelViewSet):
    queryset = ShopsModel.objects.filter(is_delete=False)
    serializer_class = ShopssSer
    lookup_url_kwarg = "pk"
    lookup_field = "pk"


# 根据商家查询菜品
class DishesAPIView(APIView):
    def get(self, request,id):
        # did  = request.data.get('did')
        goods_type = GoodTypeModel.objects.filter(shops=id).first()
        goods = goods_type.goodmodel_set.all()
        serializer_class = DishesClassifySer(goods,many=True)
        if goods:
            return Response({
                "code": 200,
                "msg": "查询到菜品",
                "data":serializer_class.data
            })
        else:
            return Response({
                "code": 204,
                "msg": "没有找到该菜品"
            })


# 根据种类查询菜品
class CaseAPIView(APIView):
    def get(self, request,id):
        # did  = request.data.get('did')
        cate_type = GoodTypeModel.objects.filter(id=id).first()
        goods = cate_type.goodmodel_set.all()
        serializer_class = DishesClassifySer(goods,many=True)
        if goods:
            return Response({
                "code": 200,
                "msg": "查询到菜品",
                "data":serializer_class.data
            })
        else:
            return Response({
                "code": 204,
                "msg": "没有找到该菜品分类下的菜"
            })


# 查询客户订单
class Shop_order(viewsets.ViewSet):
    def shop_order(self, request):
        try:
            shops_id = request.session["shops_id"]
            print(shops_id)
            order_list = OrderModel.objects.filter(shops_id=shops_id,is_delete=False).all()
            ser = OrderSer(order_list,many=True)
            order_list = ser.data
            return Response({"code": 200, "message": "ok！","order_list": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})

    # 获取订单详情
    def order_desc(self, request, pk):
        try:
            print("啊啊啊")
            shops_id = request.session.get("shops_id")
            print(">>>>>",shops_id)
            order = OrderModel.objects.filter(id=pk, shops_id=shops_id, is_delete=False).first()
            print(">>>",order)
            order_goods_list = order.ordergoodsmodel_set.all()
            order_goods = OrderGoodsSer(order_goods_list, many=True)
            order = OrderSer(order)
            order = order.data
            return Response({"code": 200, "message": "ok！", "order": order, "goods_list": order_goods.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "message": "服务器错误！"})

# 修改商品
# 修改用户
class UpGoodView(ModelViewSet):
    queryset = GoodModel.objects.all()
    serializer_class = DishesClassifySer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"

    def update(self, request, *args, **kwargs):
        try:
            shops = self.get_object()
            shops.name = request.data.get('name')
            shops.price = request.data.get('price')
            shops.image = request.data.get('image')
            shops.save()
        except:
            return Response({'code': 400, 'msg': "更新商品数据报错"})
        return Response({'code': 200, 'msg': '更新商品信息成功'})


